package com.hk.yajin.utills;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.ScaleAnimation;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.widget.ImageView;


import com.hk.developmentlib.cache.SimpleDiskCache;
import com.hk.developmentlib.utills.FastjsonUtils;
import com.hk.developmentlib.utills.FileHelper;
import com.hk.developmentlib.utills.NetworkInfoUtils;
import com.hk.developmentlib.utills.des.Des;
import com.hk.yajin.R;
import com.hk.yajin.base.MyApplication;
import com.hk.developmentlib.baseben.DeviceInfo;
import com.hk.yajin.model.UserInfo;
import com.hk.yajin.utills.constants.SharedPreferencesConstants;

import org.xutils.common.util.LogUtil;

import java.util.Comparator;
import java.util.Map;

/**
 * 常用工具类
 *
 * @author wl
 */
public class AppUtils {
    public class CacheConstants {
        /**
         * 5分钟--列表数据:wifi下(暂时改为一个小时 )
         */
        public final static long TIME_LIST_WIFI = -1;

        /**
         * 一个小时 --列表数据:移动数据流量下
         */
        public final static long TIME_LIST_GSM = -1;

        /**
         * 六个小时--用户详细信息
         */
        public final static long TIME_USERINFO = 21600000;

        /**
         * 六个小时 --活动数据
         */
        public final static long TIME_MARKET = 21600000;

        /**
         * 一个小时--玩家详细信息
         */
        public final static long TIME_GAMEPLAYER = 3600000;

        /**
         * 24个小时 -- 热门城市缓存时间
         */
        public final static long TIME_CITYS_HOT = 86400000;

        /**
         * 24个小时 -- 商品分类缓存时间
         */
        public final static long TIME_GOOD_TYPE = 86400000;


        public final static long TIME_TOPICS_TYPE = 86400000 * 30;
    }


    /**
     * 根据当前网路情况设置webview缓存模式
     *
     * @return
     */
    public static int getWebCacheMode(Context context) {
        int mode = 0;
        switch (new NetworkInfoUtils(context).getNetType()) {
            case -1:
                mode = WebSettings.LOAD_CACHE_ELSE_NETWORK;
                break;
            case 0:
                mode = WebSettings.LOAD_CACHE_ELSE_NETWORK;
                break;
            case 1:
                mode = WebSettings.LOAD_NO_CACHE;
                //mode = WebSettings.LOAD_DEFAULT;
                break;
        }
        return mode;
    }


    public static void changeBooleanPreferences(Context ct, String name, String key, Boolean value) {
        SharedPreferences defaultPreferences = ct.getSharedPreferences(name, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = defaultPreferences.edit();
        editor.putBoolean(key, value);
        editor.commit();
    }

    /**
     * 根据当前网路情况获取缓存时间
     *
     * @return
     */
    public static long getCacheTime(Context context) {
        long interval = 0;
        switch (new NetworkInfoUtils(context).getNetType()) {
            case -1:
                break;
            case 0:
                interval = CacheConstants.TIME_LIST_GSM;
                break;
            case 1:
                interval = CacheConstants.TIME_LIST_WIFI;
                break;
        }
        return interval;
    }

    public static View getFootView(Context mContext) {

        View footView = LayoutInflater.from(mContext).inflate(R.layout.footview, null);
        footView.setVisibility(View.INVISIBLE);
        ImageView img_loading = (ImageView) footView.findViewById(R.id.img_loading);
        Animation mAnimation = AnimationUtils.loadAnimation(mContext, R.anim.loading_tip);
        mAnimation.setInterpolator(new LinearInterpolator());// LinearInterpolator为匀速效果
        img_loading.startAnimation(mAnimation);

        return footView;
    }

    public static Animation getFootImaAnimation(Context mContext) {
        Animation mAnimation = AnimationUtils.loadAnimation(mContext, R.anim.loading_tip);
        mAnimation.setInterpolator(new LinearInterpolator());// LinearInterpolator为匀速效果
        return mAnimation;
    }

    static class ValueComparator implements Comparator<String> {

        Map<String, Long> base;

        public ValueComparator(Map<String, Long> base) {
            this.base = base;
        }

        // Note: this comparator imposes orderings that are inconsistent with
        // equals.
        public int compare(String a, String b) {
            if (base.get(a) >= base.get(b)) {
                return -1;
            } else {
                return 1;
            } // returning 0 would merge keys
        }
    }

    /**
     * 保存最近的搜索的词条sp
     */
    public static void saveRecentlySearchRecord(Context ct, String word) {
        SharedPreferences sp_value = ct.getSharedPreferences(
                SharedPreferencesConstants.SP_NAME_SEARCH_RECORD, ct.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp_value.edit();
        editor.putLong(word, System.currentTimeMillis());

        editor.commit();
    }

    /**
     * 删除的搜索的词条sp
     */
    public static void deleteRecentlySearchRecord(Context ct, String value) {
        SharedPreferences sp_value = ct.getSharedPreferences(
                SharedPreferencesConstants.SP_NAME_SEARCH_RECORD, ct.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp_value.edit();
        editor.remove(value);
        editor.commit();
    }

//    /**
//     * 从sp中读取最近搜索的词条
//     */
//
//    public static List<SearchRecord> getRecentlySearchRecord(Context ct, int recoedsize) {
//        List<SearchRecord> records = new ArrayList<>();
//        SharedPreferences sp_value = ct.getSharedPreferences(
//                SharedPreferencesConstants.SP_NAME_SEARCH_RECORD, ct.MODE_PRIVATE);
//        Map<String, Long> recordTimeMap = (Map<String, Long>) sp_value.getAll();
//        //Set<String> ls = recordTimeMap.keySet();
//
//
//        // 按时间排序
//        ValueComparator bvc = new ValueComparator(recordTimeMap);
//
//        TreeMap<String, Long> sorted_map = new TreeMap<String, Long>(bvc);
//        sorted_map.putAll(recordTimeMap);
//
//        int size = 0;
//        for (TreeMap.Entry<String, Long> entry : sorted_map.entrySet()) {
//            size++;
//            if (size > recoedsize) {
//                break;
//            }
//            String key = entry.getKey();
//            SearchRecord item = new SearchRecord();
//            item.setName(key);
//            item.setTime(entry.getValue());
//            records.add(item);
//        }
//
//        return records;
//    }


    /**
     * 获取设备的屏幕信息
     *
     * @param activity
     * @return
     */
    public static DeviceInfo getDevicesPix(Activity activity) {
        DisplayMetrics metric = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
        DeviceInfo deviceInfo = new DeviceInfo();
        deviceInfo.width = metric.widthPixels; // 屏幕宽度（像素）

        deviceInfo.height = metric.heightPixels; // 屏幕高度（像素）
        deviceInfo.density = metric.density; // 屏幕密度（0.75 / 1.0 / 1.5）
        deviceInfo.densityDpi = metric.densityDpi; // 屏幕密度DPI（120 / 160 / 240）

        return deviceInfo;
    }


    /**
     * 为当前点击的Item设置变大和透明度降低的动画
     *
     * @param duration
     * @return
     */
    public static Animation scaleBigAnim(int duration) {
        AnimationSet animationSet = new AnimationSet(true);

        ScaleAnimation scaleAnim = new ScaleAnimation(5.5f, 1.0f, 5.5f, 1.0f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f);
        AlphaAnimation alphaAnim = new AlphaAnimation(1f, 0.0f);

        animationSet.addAnimation(scaleAnim);
        animationSet.addAnimation(alphaAnim);

        animationSet.setDuration(duration);
//		animationSet.setFillAfter(true);
        animationSet.setFillBefore(true);
        return animationSet;

    }


//
//	/**
//	 * 根据当前网路情况获取缓存时间
//	 *
//	 * @return
//	 */
//	public static long getCacheTime(Context context) {
//		long interval = 0;
//		switch (new NetworkInfoUtils(context).getNetType()) {
//		case -1:
//			break;
//		case 0:
//			interval = CacheConstants.TIME_LIST_GSM;
//			break;
//		case 1:
//			interval = CacheConstants.TIME_LIST_WIFI;
//			break;
//		}
//		return interval;
//	}
//


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    public static void hideKeybord(Context mContext) {
        /** 隐藏软键盘 **/
        View view = ((Activity) mContext).getWindow().peekDecorView();
        if (view != null) {
            @SuppressWarnings("static-access")
            InputMethodManager inputmanger = (InputMethodManager) mContext.getSystemService(mContext.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);

        }
    }

    public static void showKeybord(Context mContext) {
        /** 弹出软键盘 **/
        View view = ((Activity) mContext).getWindow().peekDecorView();
        if (view != null) {
            @SuppressWarnings("static-access")
//            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//            imm.showSoftInput(et_dialog_confirmphoneguardpswd, InputMethodManager.SHOW_IMPLICIT);

                    InputMethodManager inputmanger = (InputMethodManager) mContext.getSystemService(mContext.INPUT_METHOD_SERVICE);
            inputmanger.showSoftInputFromInputMethod(view.getWindowToken(), InputMethodManager.SHOW_IMPLICIT);
        }
    }

    public static void copyToboard(Context ct, String text) {
        if (ct == null || TextUtils.isEmpty(text)) {
            return;
        } else {
            ClipboardManager clipboardManager = (ClipboardManager) ct.getSystemService(Context.CLIPBOARD_SERVICE);
            clipboardManager.setPrimaryClip(ClipData.newPlainText(null, text));
        }
    }

    public static boolean checkHasCacheAcount(Context ct) {

        SharedPreferences sp = ct.getSharedPreferences(SharedPreferencesConstants.SP_NAME_USERINFO, ct.MODE_PRIVATE);

        String acount = "";
        try {
            acount = Des.decryptDES(sp.getString("ac", ""), SimpleDiskCache.YJ_DES_KEY);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (!TextUtils.isEmpty(acount)) {
            return true;
        } else {
            return false;
        }
    }

    public static void SaveOrClearInstanceState(Context ct, int type) {
        LogUtil.e("Application1");
        SharedPreferences runingPreferences = ct.getSharedPreferences(SharedPreferencesConstants.SP_KEY_RUNING_USER, Context.MODE_PRIVATE);
        LogUtil.e("Application2");
        switch (type) {
            // save
            case 0:
                if (MyApplication.loginUser != null) {
                    String user_st = FastjsonUtils.toJSONString(MyApplication.loginUser);
                    SharedPreferences.Editor editor = runingPreferences.edit();
                    editor.putString("runing_user", user_st);
                    editor.commit();
                }
                break;
            // get
            case 1:
                if (checkHasCacheAcount(ct)) {
                    String user_st = runingPreferences.getString("runing_user", "");
                    // LogUtil.d("登录请求失败读缓存：" + user_st);
                    MyApplication.loginUser = (UserInfo) FastjsonUtils.getBeanObject(user_st, UserInfo.class);
                }
                break;
            // clear
            case 2:
                MyApplication.loginUser = null;
                SharedPreferences.Editor editor = runingPreferences.edit();
                editor.putString("runing_user", "");
                editor.commit();
                break;
        }
    }
}
